<template>
    <el-card>
        <div class="search-query">
            <el-form :inline="true" :model="searchForm" ref="searchFormRef">
                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="searchForm.name" placeholder="角色名称" clearable />
                </el-form-item>
                <el-form-item label="角色编码" prop="code">
                    <el-input v-model="searchForm.code" placeholder="角色编码" clearable />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="handleSearchReset(searchFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="table-btn">
            <el-space :size="10">
                <el-button type="primary" @click="handleAddView">新增</el-button>
                <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
            </el-space>

            <el-button type="primary" @click="handleReflesh">刷新</el-button>
        </div>

        <el-table border :data="roleData.list" v-loading="loading" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="code" label="角色编码" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column prop="updateTime" label="更新时间" />
            <el-table-column fixed="right" label="操作">
                <template v-slot="scope" #default>
                    <el-button type="primary" @click="handleAssign(scope.row)" link>分配权限</el-button>
                    <el-button type="success" @click="handleEdit(scope.row)" link>编辑</el-button>
                    <el-button type="danger" @click="handleDelete(scope.row)" link>删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="roleData.currentPage" v-model:page-size="roleData.pageSize"
            :page-sizes="[10, 20, 50, 100]" background="background" layout="total, sizes, prev, pager, next,jumper"
            :total="roleData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑 -->
    <el-dialog v-model="visible" :title="saveForm.id ? '编辑' : '新增'" width="500" :close-on-click-modal="false">
        <el-form :model="saveForm" label-position="top" :rules="rules" ref="saveFormRef">
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="saveForm.name" placeholder="角色名称" clearable />
            </el-form-item>
            <el-form-item label="角色编码" prop="code">
                <el-input  v-model="saveForm.code" placeholder="角色编码" clearable />
            </el-form-item>
        </el-form>
        <template #footer>
            <div>
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd(saveFormRef)">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="js">

import { ref,onMounted } from 'vue'
import role from '@/services/role'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const roleData = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    list: []
})

const visible = ref(false)
const saveFormRef = ref()
const saveForm = ref({
    id: '',
    name: '',
    code: ''
})

const rules = ref({
    name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
    ],
    code: [
        { required: true, message: '请输入角色编码', trigger: 'blur' },

    ]
})


const init = async () => {
    loading.value = true
    const res = await role.page({})
    if(res.code == 200) {
        roleData.value = res.data
        loading.value = false
    }
}

onMounted(()=>{
    init()
})

const handleEdit = (row) => {
    saveForm.value = JSON.parse(JSON.stringify(row)) // 改过之后的
    visible.value = true
}

const handleDelete = async (row) => {
    const res = await role.deleteByIds([row.id])
    if (res.code === 200) {
        init()
        ElMessage({
            type: 'success',
            message: res.msg
        })
    }
}

let ids = []
const handleSelectionChange =  (value) => {
    ids = []
    value.forEach(e => {
        ids.push(e.id)
    });
}

const handleAddView = () =>{
    visible.value = true
    saveForm.value = {}
}

const handleAdd = async (formRef) => {
    if (!formRef) return
    await formRef.validate((valid, fields) => {
        if (valid) {
            role.save(saveForm.value).then((res) => {
                if (res.code == 200) {
                    ElMessage({
                        message: res.msg,
                        type: 'success'
                    })
                    init()
                }
            })

            visible.value = false
        } else {
            console.log('error submit!', fields)
        }
    })
}

const handleBatchDelete = async () => {
    if(ids.length == 0) {
        throw ElMessage({
            type: 'warning',
            message: "请选择"
        })
    }
    const res = await role.deleteByIds(ids)
    if (res.code === 200) {
        init()
        ElMessage({
            type: 'success',
            message: res.msg
        })
    }
}

const handleReflesh = () => {
    init()
}

const searchFormRef = ref()
const searchForm = ref({
    name: '',
    code: ''
})
// 搜素
const handleSearch = async () => {
    loading.value = true
    const res = await role.page(searchForm.value)
    if (res.code === 200) {
        roleData.value = res.data
        loading.value = false
    }
}
// 搜索重置
const handleSearchReset = (formRef) => {
    formRef.resetFields()
}

// 当前页大小
const handleSizeChange = async (pageSize) => {
    loading.value = true
    const res = await role.page({ pageSize })
    if (res.code === 200) {
        roleData.value = res.data
        loading.value = false
    }
}

// 当前页数
const handleCurrentChange = async (currentPage) => {
    loading.value = true
    const res = await role.page({ currentPage })
    if (res.code === 200) {
        role.value = res.data
        loading.value = false
    }
}

// 分配权限
const handleAssign = () =>{

}

</script>

<style lang="less" scoped>
.table-btn {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
}
</style>